1 ///////////////////////////////////////////////////////////////
2 // Knuth-Morris-Pratt algorithm for string matching //
3 // Complexity: O(n + m) //
4 ///////////////////////////////////////////////////////////////
6 // Reports all occurrences of 'needle' in 'haystack'.
7 void kmp(const string
&needle
, const string
&haystack
) {
8 // Precompute border function
10 vector
<int> border(m
+ 1);
12 for (int i
= 0; i
< m
; ++i
) {
13 border
[i
+1] = border
[i
];
14 while (border
[i
+1] > -1 and
15 needle
[border
[i
+1]] != needle
[i
]) {
16 border
[i
+1] = border
[border
[i
+1]];
21 // Now the actual matching
22 int n
= haystack
.size();
24 for (int i
= 0; i
< n
; ++i
){
25 while (seen
> -1 and needle
[seen
] != haystack
[i
]) {
29 printf("Needle occurs from %d to %d\n", i
- m
+ 1, i
);